package com.xzakota.minesweeper.db;

import com.xzakota.minesweeper.log.XLogger;
import com.xzakota.minesweeper.util.ResourceUtil;

import java.io.InputStream;
import java.sql.*;
import java.util.Properties;

/**
 * 数据库连接驱动
 *
 * @author Xzakota
 */
public class ConnectionManager {
    // 是否有凭据
    private static boolean hasCredential = false;

    // JDBC 配置
    private static String dbURL;
    private static String dbUsername;
    private static String dbPassword;

    private ConnectionManager() {
    }

    /**
     * 初始化凭据
     */
    public static void initCredential() {
        Properties props = new Properties();
        try (InputStream input = ResourceUtil.getResourceAsStream("db.properties")) {
            props.load(input);
            dbURL = props.getProperty("db.jdbc.url");
            dbUsername = props.getProperty("db.username");
            dbPassword = props.getProperty("db.password");
            hasCredential = true;

            XLogger.info("读取数据库凭据成功: " + dbUsername);
        } catch (Exception e) {
            throw new RuntimeException("读取数据库凭据失败", e);
        }
    }

    /**
     * @return 获取数据库连接会话
     */
    public static Connection getConnection() {
        Connection connection;
        try {
            if (hasCredential) {
                connection = DriverManager.getConnection(dbURL, dbUsername, dbPassword);
                // XLogger.info("连接数据库成功");
            } else {
                throw new RuntimeException("连接数据库失败: 未找到凭据或凭据错误");
            }
        } catch (SQLException e) {
            throw new RuntimeException("连接数据库失败", e);
        }
        return connection;
    }

    /**
     * 释放资源
     */
    public static void release(ResultSet rs, PreparedStatement ps, Connection con) {
        try {
            if (rs != null) {
                rs.close();
            }
            if (ps != null) {
                ps.close();
            }
            if (con != null) {
                con.close();
            }
            // XLogger.info("数据库连接关闭成功");
        } catch (SQLException e) {
            throw new RuntimeException("数据库连接关闭失败", e);
        }
    }
}
